package controllers;

import java.util.Arrays;
import java.util.List;

import play.data.validation.IsTrue;
import play.data.validation.Required;
import play.mvc.Controller;
import client.RestException;
import client.YouGoClient;

import com.ineatconseil.yougo.dto.RequestDto;
import com.ineatconseil.yougo.dto.RequestStatusDto;
import com.ineatconseil.yougo.dto.UserDto;
import com.ineatconseil.yougo.dto.UserTypeDto;

public class ManageUser extends Controller {
	public static YouGoClient client = new YouGoClient();

	public static void index() throws RestException {

		List<UserDto> userList = Arrays.asList(client.getUserDtos());
		List<UserTypeDto> types = Arrays.asList(client.getUserTypeDto());
		//ValuePaginator paginator = new ValuePaginator(userList);
		//render(paginator, types);
		render(userList, types);

	}

	public static void deleteUser(String userID) throws NumberFormatException, RestException {

		if (!session.get("userid").equals(userID)) {
			client.deleteUserDto(new Long(userID));
			index();
		} else {
			index();
		}

	}
	
	public static void edit(Long userID) throws NumberFormatException, RestException {
		List<UserTypeDto> userTypes = Arrays.asList(client.getUserTypeDto());
		if(userID != null) {
			UserDto user = client.getUserDtoById(userID);
			render(user,userTypes);
		}
		render(userTypes);
	}

	/**
	 * Update ou creation d'un nouvel utilisateur
	 * @param userID
	 * @param fullName
	 * @param email
	 * @param active
	 * @param admin
	 * @param userType
	 * @throws NumberFormatException
	 * @throws RestException
	 */
	public static void save(Long userID, @Required String fullName, @Required String email, 
							String active,  String admin, @Required Long userType) throws NumberFormatException, RestException {
		if (!validation.hasErrors()) {
			UserDto user = new UserDto();
			user.setFullName(fullName);
			user.setEmail(email);
			user.setTypeId(userType);
			//String to check value of a checkbox
			String undefined = "undefined";
			user.setAdmin((admin.equals(undefined)) ? false : true);
			user.setActive((active.equals(undefined)) ? false : true);
			user.setId((userID == null) ? null : userID);
//			if (!start.equals(end)) {
//				validation.future(start);
//				validation.future(end);
//				validation.future(end, start);
//			}
//
//			if (!validation.hasErrors()) {
//				Long userid = new Long(session.get("userid"));
//				RequestDto req = new RequestDto();
//				req.setAskComment(observations);
//				req.setId(null);
//				req.setFrom(start);
//				req.setTo(end);
//				req.setStatus(RequestStatusDto.PENDING);
//				req.setTypeId(requesttype);
//				client.postRequestDtos(userid, req);
//			}
		}
		params.flash();
	//	validation.keep();
		//edit(userID);
	}
	
}
